package com.ev.hr.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.ev.custom.vo.ClientEntity;
import com.ev.framework.il8n.MessageSourceHandler;
import com.ev.framework.utils.BeanUtils;
import com.ev.framework.utils.StringUtils;
import com.ev.hr.domain.EmployeeInfoDO;
import com.ev.hr.service.EmployeeInfoService;
import com.ev.hr.vo.AttendanceRecordImportParam;
import com.ev.system.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.ev.hr.dao.AttendanceRecordDao;
import com.ev.hr.domain.AttendanceRecordDO;
import com.ev.hr.service.AttendanceRecordService;
import com.ev.hr.vo.AttendanceRecordPageParam;
import com.ev.framework.utils.R;
import com.ev.apis.model.DsResultResponse;
import com.google.common.collect.Maps;
import org.springframework.web.multipart.MultipartFile;


@Service
public class AttendanceRecordServiceImpl implements AttendanceRecordService {
	@Autowired
	private AttendanceRecordDao attendanceRecordDao;

	@Autowired
	private RoleService roleService;


	@Autowired
	private MessageSourceHandler messageSourceHandler;

	@Autowired
	private EmployeeInfoService employeeInfoService;
	
	@Override
	public AttendanceRecordDO get(Long id){
		return attendanceRecordDao.get(id);
	}
	
	@Override
	public List<AttendanceRecordDO> list(Map<String, Object> map){
		return attendanceRecordDao.list(map);
	}
	
	@Override
	public int count(Map<String, Object> map){
		return attendanceRecordDao.count(map);
	}
	
	@Override
	public int save(AttendanceRecordDO attendanceRecord){
		return attendanceRecordDao.save(attendanceRecord);
	}
	
	@Override
	public int update(AttendanceRecordDO attendanceRecord){
		return attendanceRecordDao.update(attendanceRecord);
	}

	@Override
	public int updateAll(AttendanceRecordDO attendanceRecord){
		return attendanceRecordDao.updateAll(attendanceRecord);
	}
	
	@Override
	public int remove(Long id){
		return attendanceRecordDao.remove(id);
	}
	
	@Override
	public int batchRemove(Long[] ids){
		return attendanceRecordDao.batchRemove(ids);
	}

	@Override
	public R saveAndVerify(AttendanceRecordDO saveParam){
		if(saveParam.getId()!=null){
			return attendanceRecordDao.update(saveParam)>0?R.ok():R.error();
		}
		return attendanceRecordDao.save(saveParam)>0?R.ok():R.error();
	}

	@Override
	public Map<String, Object> getById(Long id) {
		AttendanceRecordDO attendanceRecord = attendanceRecordDao.get(id);
		if (attendanceRecord != null) {
			Map<String,Object> result = Maps.newHashMap();
			result.put("data",attendanceRecord);
			return R.ok(result);
		}
		return R.error();
	}

	@Override
	public Map<String, Object> pageList(AttendanceRecordPageParam pageParam) {
		Map<String,Object> result = Maps.newHashMap();
		JSONObject o = (JSONObject) JSONObject.toJSON(pageParam);
		o.putAll(roleService.getDataPermission(3));

		List<Map<String, Object>> data = attendanceRecordDao.pageList(o);
		int total = attendanceRecordDao.pageCount(o);
		result.put("data", new DsResultResponse(pageParam.getPageno(),pageParam.getPagesize(),total,data));
		return R.ok(result);
	}

	@Override
	public R importRecord(MultipartFile file) {
		if (file.isEmpty()) {
			return R.error(messageSourceHandler.getMessage("file.nonSelect", null));
		}
		ImportParams params = new ImportParams();
		params.setTitleRows(0);
		params.setHeadRows(1);
		params.setNeedVerify(true);
		String[] importFields = {"所属时期"};
		params.setImportFields(importFields);
		List<AttendanceRecordImportParam> attendanceRecordImportParamList;
		List<AttendanceRecordImportParam> failList;
		try {
			ExcelImportResult<AttendanceRecordImportParam> result  =  ExcelImportUtil.importExcelMore(file.getInputStream(), AttendanceRecordImportParam.class, params);
			failList = result.getFailList();
			attendanceRecordImportParamList = result.getList();
			attendanceRecordImportParamList = attendanceRecordImportParamList
					.stream()
					.filter(e-> StringUtils.isNoneEmpty(e.getEmployeeCode()))
					.collect(Collectors.toList());
		}catch(Exception e) {
			return R.error(messageSourceHandler.getMessage("file.upload.error", null));
		}
		if(failList.size()>0){
			StringBuilder stringBuilder = new StringBuilder();
			for(AttendanceRecordImportParam attendanceRecordImportParam : failList){
				stringBuilder.append("行标识【期间】"+attendanceRecordImportParam.getPeriod()+"【工号】"+attendanceRecordImportParam.getEmployeeCode()+":"+
						attendanceRecordImportParam.getMessage()+"<br/>");
			}
			return R.error(messageSourceHandler.getMessage("file.validation.error", new String[]{stringBuilder.toString()}));
		}


		if(attendanceRecordImportParamList.size()>0){
			//获取已经导入的
			List<AttendanceRecordDO> repeatList = new ArrayList<AttendanceRecordDO>();
			List<AttendanceRecordDO> noRepeatList = new ArrayList<AttendanceRecordDO>();
			List<AttendanceRecordDO> attendanceRecordDOList = list(null);
			List<EmployeeInfoDO> employeeInfoDOList = employeeInfoService.list(null);
			List<String> noHasEmployeeList = new ArrayList<>();
			for(AttendanceRecordImportParam attendanceRecord : attendanceRecordImportParamList){
				List<EmployeeInfoDO> employeeInfoDOS = employeeInfoDOList.stream()
						.filter(e->StringUtils.equals(attendanceRecord.getEmployeeCode(),e.getEmployeeCode()))
						.collect(Collectors.toList());
				if(employeeInfoDOS.size()>0){
					List<AttendanceRecordDO> hasList = attendanceRecordDOList.stream()
							.filter(e-> StringUtils.equals(attendanceRecord.getEmployeeCode(),e.getEmployeeCode()) &&
							StringUtils.equals(attendanceRecord.getPeriod(),e.getPeriod()))
							.collect(Collectors.toList());
					if(hasList.size()>0){
						AttendanceRecordDO repeatDo = hasList.get(0);
						BeanUtils.copyProperties(attendanceRecord,repeatDo);
						repeatDo.setEmployeeId(employeeInfoDOS.get(0).getId());
						repeatDo.setEmployeeName(employeeInfoDOS.get(0).getEmployeeName());
						repeatDo.setEmployeeName(employeeInfoDOS.get(0).getEmployeeName());
						repeatDo.setDeptId(employeeInfoDOS.get(0).getDeptId());
						repeatList.add(repeatDo);
					}else{
						AttendanceRecordDO noRepeatDo = new AttendanceRecordDO();
						BeanUtils.copyProperties(attendanceRecord,noRepeatDo);
						noRepeatDo.setEmployeeId(employeeInfoDOS.get(0).getId());
						noRepeatDo.setEmployeeName(employeeInfoDOS.get(0).getEmployeeName());
						noRepeatDo.setDeptId(employeeInfoDOS.get(0).getDeptId());
						noRepeatList.add(noRepeatDo);
					}
				}else{
					noHasEmployeeList.add(attendanceRecord.getEmployeeCode());
				}

			}
			if(noHasEmployeeList.size()>0){
				return R.error(messageSourceHandler.getMessage("hr.employee.noHas", new String[]{noHasEmployeeList.toString()}));
			}

			if(repeatList.size()>0){
				attendanceRecordDao.batchUpdate(repeatList);
			}
			if(noRepeatList.size()>0){
				attendanceRecordDao.batchSave(noRepeatList);
			}

		}
		return R.ok();
	}

	@Override
	public List<Map<String, Object>> getList(Map<String, Object> map) {
		return attendanceRecordDao.getList(map);
	}
}
